﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace SAM.Framework.Security
{
    public class Md5Provider : ISecurity
    {
        /// <summary>
        /// 对称加密的向量
        /// </summary>
        private readonly byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x9A, 0xAB, 0xCD, 0xEF };

        public string Escape(string encryptString, string entryptKey)
        {
            if (entryptKey.Length != 8) return string.Empty;

            byte[] byteKey = Encoding.UTF8.GetBytes(entryptKey);
            byte[] byteArray = Encoding.UTF8.GetBytes(encryptString);

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            CryptoStream cStream = new CryptoStream(stream, des.CreateEncryptor(byteKey, Keys), CryptoStreamMode.Write);
            cStream.Write(byteArray, 0, byteArray.Length);
            cStream.FlushFinalBlock();
            var ret = Convert.ToBase64String(stream.ToArray());
            cStream.Close();
            stream.Close();
            cStream = null;
            stream = null;
            return ret;
        }

        public string SecurityTextForMd5(string str)
        {
            MD5CryptoServiceProvider mD5CryptoServiceProvider = new MD5CryptoServiceProvider();
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
            var hashkey = mD5CryptoServiceProvider.ComputeHash(bytes);
            string resule = BitConverter.ToString(hashkey);
            return resule.Replace("-", "");
        }

        public string Unescape(string encryptString, string entryptKey)
        {
            if (entryptKey.Length != 8) return string.Empty;

            byte[] byteKey = Encoding.UTF8.GetBytes(entryptKey);
            byte[] byteArray = Convert.FromBase64String(encryptString);

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            CryptoStream cStream = new CryptoStream(stream, des.CreateDecryptor(byteKey, Keys), CryptoStreamMode.Write);
            cStream.Write(byteArray, 0, byteArray.Length);
            cStream.FlushFinalBlock();
            var ret = Encoding.UTF8.GetString(stream.ToArray());
            cStream.Close();
            stream.Close();
            cStream = null;
            stream = null;
            return ret;
        }
    }
}
